//index.js
//获取应用实例
const app = getApp()

const util = require("../../utils/util");
const db = wx.cloud.database();
const _ = db.command;
const db_orders = db.collection('orders');

Page({
  data: {

    userInfo: {},
    show: false,
    extraOrderDate: '',
    myOrderDate: '',
    orderList: [],
    listHidden: false,
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    formatter(day) {
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();
      if (date === new Date().getDate()) {
        day.bottomInfo = '今天';
      }
      return day;
    }
  },
  //检查订餐时间是否超过范围，可以订餐返回true
  checkOrderTime(d) {
    console.log(util.formatDate(new Date()).time) //午餐
    let currDate = new Date()
    let orderDate = this.data.myOrderDate
    let seven_day = (orderDate.getTime() - currDate.getTime()) / (1000 * 60 * 60 * 24)

    if (parseInt(seven_day) >= 7) {
      wx.showToast({
        title: '只能提前订一周的餐。',
        icon: 'none'
      })
      return false
    }

    if (this.data.orderType == 1 && this.data.extraOrderDate == util.formatDate(currDate).date_week && currDate.getHours() > 9) {
      wx.showToast({
        title: '已超出订餐时间。',
        icon: 'none'
      })
      return false
    } else if (this.data.orderType == 2 && this.data.extraOrderDate == util.formatDate(currDate).date_week && currDate.getHours() > 12) {
      wx.showToast({
        title: '已超出订餐时间。',
        icon: 'none'
      })
      return false
    } else if (this.data.orderType == 3 && this.data.extraOrderDate == util.formatDate(currDate).date_week && currDate.getHours() > 17) {
      wx.showToast({
        title: '已超出订餐时间。',
        icon: 'none'
      })
      return false
    } else {
      return true
    }

  },
  // 撤餐
  delOrder(e) {
    let id = e.currentTarget.dataset.id;
    console.log(e)
    db_orders.doc(id).get().then(res => {
      const order = res.data
      const day = util.checkDay(new Date(), order.extra_order_date.split('.')[0]).day
      if (day * 24 < 48) {
        util.tips('48小时以内的不允许撤餐')
        return false
      }
  
      db_orders.doc(id).remove({
        success: res => {
          console.log(res)
          this.setData({
            // addHidden: false
          });
          wx.showToast({
            title: '撤餐成功',
            icon: 'none'
          })
          this.getOrderList();
        },
        fail: err => {
          wx.showToast({
            title: '撤餐失败',
            icon: 'none'
          });
          console.error('[数据库] [删除记录] 失败：', err)
        }
      })
      
    }).catch(err => {
      console.error(err)
    })
    
  },

  // 获取订餐列表
  getOrderList(date) {
    console.log(this.data.userInfo.name)
    console.log(date == null)
    console.log(util.formatDate(new Date()).date_week)
    db_orders.where({
      person: this.data.userInfo.name,
      number: this.data.userInfo.number,
      extra_order_date: date != null ? _.eq(date) : _.gte(util.formatDate(new Date()).date_week)
    }).get({
      success: res => {
        console.log(res.data)
        this.setData({
          orderList: res.data
        });
      },
      fail: err => {
        console.error(err)
      }
    })
  },

  chooseDate() {
    this.setData({
      show: true
    });
    console.log(this.data.show)
  },
  onDisplay() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onConfirm(event) {
    this.setData({
      show: false,
      myOrderDate: event.detail,
      extraOrderDate: util.formatDate(event.detail).date_week,
    });
    this.getOrderList(this.data.extraOrderDate)
    // this.isOrderedByDay(this.data.extraOrderDate);
  },

  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },


  onReady: function () {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(util.formatDate(new Date()).date_week)
    this.setData({
      // userInfo: app.globalData.userInfo,
      userInfo: wx.getStorageSync('userInfo'),
      myOrderDate: new Date(),
      // extraOrderDate: util.formatDate(new Date()).date_week
    });

    this.getOrderList();
  },
  choosePay: function (e) {
    this.setData({
      payment: e.target.dataset.pay
    })
    switch (e.target.dataset.pay) {
      case '03':
        this.setData({
          paymentText: "企业码"
        })
        break;
      case '02':
        this.setData({
          paymentText: "积分"
        })
        break;
      default:
        this.setData({
          paymentText: "微信"
        })
    }
    this.closeMask()
  },
  closeMask: function () {
    this.setData({
      maskShow: true
    })
  },


})